<template>
    <div class="authority">
        <div class="gva-search-box">
            <el-form ref="searchForm" :inline="true">
                <el-form-item label="行政区划">
                    <el-cascader style="width: 90%" :options="areaList" :props="props1" v-model="searchPids"
                        @change="searchAreaChange" />
                </el-form-item>
                <el-form-item label="楼栋名称">
                    <el-input v-model="searchInfo.name" style="width:170px" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="详细地址">
                    <el-input v-model="searchInfo.address" style="width:170px" placeholder="请输入" />
                </el-form-item>
                <el-form-item style="margin-right: 0;">
                    <el-button type="primary" icon="search" @click="onSubmit">
                        查询
                    </el-button>
                    <el-button icon="refresh" @click="onReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="gva-table-box unit">
            <el-table :data="tableData" row-key="id">
                <el-table-column type="index" label="序号" width="100" />
                <el-table-column align="left" label="办公楼名称" prop="name" width="300"></el-table-column>
                <el-table-column align="left" label="详细地址" prop="areaAddress" width="300"></el-table-column>
                <el-table-column align="left" label="总建筑面积" prop="totalArea"></el-table-column>
                <el-table-column align="left" label="总层数" prop="totalFloor"></el-table-column>
                <el-table-column align="left" fixed="right" label="操作" min-width="160">
                    <template #default="scope">
                        <span @click="openCard(scope.row,'id')" style="color: green;cursor: pointer;">查看卡片</span>
                        <span style="margin: 0 5px;">/</span>
                        <span style="color: darkorange;cursor: pointer;" @click="openYtgf(scope.row)">以图管房</span>
                    </template>
                </el-table-column>
            </el-table>
            <div class="gva-pagination">
                <el-pagination v-model:current-page="page" :page-size="pageSize" :total="total"
                    layout="prev, pager, next" @current-change="handleCurrentChange" />
            </div>
        </div>
        <ldCard ref="cardRef"></ldCard>
        <ytgf ref="ytgfRef"></ytgf>
    </div>
</template>
<script setup>
import {
    getAllBgqList,
    getLouDongList,
    deleteLouDong,
    createLouDong,
    updateLouDong,
    getQuanShuList,
    deleteQuanShu,
    createQuanShu,
    updateQuanShu,
    setPicture,
    getBuildingFloors,
    savePicture,
    removePicture,
    getFangJianList,
    deleteFangJian,
    createFangJian,
    updateFangJian
} from '@/api/shujuchuli'
import {
    getRegionList,
    buildingProperty,
    unitLedger
} from '@/api/unit'
import { sources, qsdjList } from '@/utils/constant'
import { reactive, ref, onMounted, computed } from 'vue'
import { useAppStore } from "@/pinia";
import { useUserStore } from '@/pinia/modules/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import AMapLoader from '@amap/amap-jsapi-loader'; //引入
import ldCard from '@/components/ldCard.vue'
import ytgf from '@/components/ytgf.vue'

defineOptions({
    name: 'Loudong'
})
const appStore = useAppStore()


const props1 = {
    checkStrictly: true,
    label: 'name',
    value: 'id'
}


const buildingStructs = ref([
    {
        label: '框架结构（框剪结构）',
        value: 1
    },
    {
        label: '砖木',
        value: 2
    },
    {
        label: '砖混',
        value: 3
    },
    {
        label: '钢结构',
        value: 4
    }
])
const searchInfo = ref({
    name: '',
    address: '',
    regionId: ''
})
const cardRef = ref(null)
const ytgfRef = ref(null)
function openCard(row,val){
  if(cardRef.value){
    cardRef.value.openCard(row,val)
  }
}
function openYtgf(row){
  if(ytgfRef.value){
    ytgfRef.value.openCard(row)
  }
}
const userStore = useUserStore()
const headerOdj = ref({ token: userStore.token })
const adminUrl = ref('')
adminUrl.value = import.meta.env.VITE_BASE_PATH + '/file/upload'
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const dialogFormVisible = ref(false)

const quanshuDialog = ref(false)

const rules = reactive({
    name: [{ required: true, message: '请输入办公楼名称', trigger: 'blur' }],
    areaId: [{ required: true, message: '请选择所属办公区域', trigger: 'change' }],
    buildingNo: [{ required: true, message: '请输入楼栋号', trigger: 'blur' }],
    unitNo: [{ required: true, message: '请输入单元号', trigger: 'blur' }],
    center: [{ required: true, message: '请选择办公楼所属行政区划', trigger: 'change' }],
    ownership: [{ required: true, message: '请选择权属登记情况', trigger: 'change' }],
    createYear: [{ required: true, message: '请输入建设年代', trigger: 'blur' }],
    buildingUse: [{ required: true, message: '请选择楼栋用途', trigger: 'change' }],
    assetValue: [{ required: true, message: '请输入资产价值', trigger: 'blur' }],
    floorPosition: [{ required: true, message: '请输入楼层位置', trigger: 'blur' }],
    totalArea: [{ required: true, message: '请输入总建筑面积', trigger: 'blur' }],
    totalUseArea: [{ required: true, message: '请输入总使用面积', trigger: 'blur' }],
    coverArea: [{ required: true, message: '请输入占地面积', trigger: 'blur' }],
    overgroundFloor: [{ required: true, message: '请输入地上层数', trigger: 'blur' }],
    undergroundFloor: [{ required: true, message: '请输入地下层数', trigger: 'blur' }],
})
const quanshuRules = reactive({
    certificateNo: [{ required: true, message: '请输入产权证号', trigger: 'blur' }],
    obligee: [{ required: true, message: '请输入权利人', trigger: 'blur' }],
    commonSituation: [{ required: true, message: '请选择共有情况', trigger: 'change' }],
    buildingArea: [{ required: true, message: '请输入房屋建筑面积', trigger: 'blur' }]
})
let validateImage = (rule, value, callback) => {
    if (!waiguanForms.value.picture) {
        callback(new Error('请上传图片'))
    } else {
        callback()
    }
}
const waiguanRules = reactive({
    picture: [{ required: true, validator: validateImage, trigger: 'change' }],
})

const loudongForm = ref(null)
const quanshuForm = ref(null)
const initForm = () => {
    loudongForm.value.resetFields()
    form.value = {
        areaId: '',
        address: '',
        main: 1,
        name: '',
        buildingNo: '',
        unitNo: '',
        center: '',
        ownership: '',
        createYear: '',
        source: 1,
        buildingType: 1,
        buildingUse: [],
        buildingStruct: 1,
        lift: 1,
        assetValue: '',
        tag: 1,
        totalArea: '',
        totalUseArea: '',
        coverArea: '',
        overgroundFloor: '',
        undergroundFloor: '',
        totalFloor: '',
        floorPosition: ''
    }
    pids.value = []
}
const initQuanShuForm = () => {
    quanshuForm.value.resetFields()
    quanshuForms.value = {
        buildingArea: '',
        buildingId: '',
        certificateNo: '',
        commonSituation: '',
        erCode: '',
        landUseRightArea: '',
        map: '',
        obligee: '',
        otherRight: '',
        propertyCert: '',
        purpose: '',
        realEstateUnitNo: '',
        rightNature: '',
        rightType: '',
        serviceLife: '',
        splitting: ''
    }
    quanshuForms.value.buildingId = idsParam.value.buildingId
    fileList1.value = []
    fileList2.value = []
    fileList3.value = []
    fileList4.value = []
}

const isEdit = ref(false)
const dialogTitle = ref('新增办公楼')
const addLouDong = () => {
    dialogTitle.value = '新增办公楼'
    isEdit.value = false
    dialogFormVisible.value = true
}
const isQuanShuEdit = ref(false)
const quanshuTitle = ref('新增权属信息')
const quanshuVisible = ref(false)
const addQuanShu = () => {
    quanshuTitle.value = '新增权属信息'
    isQuanShuEdit.value = false
    quanshuVisible.value = true
}
const closeDialog = () => {
    initForm()
    dialogFormVisible.value = false
}
const closeDialog3 = () => {
    initQuanShuForm()
    quanshuVisible.value = false
}
const handleClose = (done) => {
    initForm()
    done()
}

const handleClose2 = (done) => {
    quanshuDialog.value = false
}
const handleClose3 = (done) => {
    quanshuVisible.value = false
}

const handleCurrentChange = (val) => {
    page.value = val
    getTableData()
}
const tableData = ref([])

const quanshuData = ref([])

// 查询
const getTableData = async () => {
    const res = await getLouDongList({
        pageNumber: page.value,
        pageSize: pageSize.value,
        ...searchInfo.value
    })
    if (res.code == 200) {
        tableData.value = res.result.data
        total.value = res.result.total
    }
}
const idsParam = ref({
    buildingId: ''
})
const wuyeData = ref([])
const useData = ref([])
const getAllData = async () => {
    const res1 = await getQuanShuList(idsParam.value.buildingId)
    if (res1.code == 200) {
        quanshuData.value = res1.result
    }
    const res2 = await buildingProperty(idsParam.value.buildingId)
    if (res2.code == 200) {
        wuyeData.value = res2.result
    }
    const res3 = await unitLedger({ buildingId: idsParam.value.buildingId })
    if (res3.code == 200) {
        useData.value = res3.result.data
    }
    cardDialog.value = true
}
getTableData()
const qyList = ref([])
const areaList = ref([])
onMounted(() => {
    getAllBgqList().then(res => {
        qyList.value = res.result
    })
    getRegionList().then(res => {
        areaList.value = res.result
    })
})

const pids = ref([])
function changeArea(val) {
    form.value.address = qyList.value.find(item => item.id == val).address
}
const areaChange = (val) => {
    form.value.center = val[val.length - 1]
}
const searchAreaChange = (val) => {
    searchInfo.value.regionId = val[val.length - 1]
}
const enterDialog = async () => {
    loudongForm.value.validate(async (valid) => {
        if (valid) {
            if (Array.isArray(form.value.buildingUse)) {
                form.value.buildingUse = form.value.buildingUse.join(',')
            }
            form.value.totalFloor = totalFloor.value
            let res
            if (isEdit.value) {
                res = await updateLouDong(form.value)
            } else {
                res = await createLouDong(form.value)
            }
            if (res.code == 200) {
                ElMessage({
                    type: 'success',
                    message: isEdit.value ? '编辑成功' : '添加成功!'
                })
                getTableData()
            }
            initForm()
            dialogFormVisible.value = false
        }
    })
}

const onSubmit = () => {
    page.value = 1
    getTableData()
}
const searchPids = ref([])
const onReset = () => {
    searchInfo.value = {
        name: '',
        address: '',
        regionId: ''
    }
    searchPids.value = []
    getTableData()
}

const waiguanForm = ref(null)
const waiguanForms = ref({
    buildingId: '',
    picture: ''
})

const loucengData = ref([])
const getLouCengData = async (val) => {
    const res = await getBuildingFloors(loucengForms.value.buildingId)
    if (res.code == 200) {
        loucengData.value = res.result
        if (val == 'floorId') {
            fangjianForms.value.floorId = loucengData.value[currentLouCeng.value].id
            getFangJianData()
        }
    }
}
const loucengDialog = ref(false)
const loucengForms = ref({
    buildingId: ''
})
const openLouCeng = (id) => {
    loucengForms.value.buildingId = id
    loucengDialog.value = true
    getLouCengData()
}
const weizhiDialog = ref(false)

const map = ref(null)
const AMaps = ref(null)
let geocoder = null; // 地图编码转换器
const initMap = (address) => {
    window._AMapSecurityConfig = {
        securityJsCode: "f84f4022a6c10294d1b19ff9b77c31c5",
    };
    AMapLoader.load({
        key: "c1c5d63a1bfa553591a271f0cb521fc1", //此处填入我们注册账号后获取的Key
        version: "2.0", //指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Geocoder"], //需要使用的的插件列表，如比例尺'AMap.Scale'等
    }).then((AMap) => {
        AMaps.value = AMap
        geocoder = new AMap.Geocoder({
            city: address, // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
        })
        geocoder.getLocation(address, function (status, result) {
            if (status === "complete" && result.info === "OK") {
                let location = [
                    result.geocodes[0].location.lng,
                    result.geocodes[0].location.lat,
                ];
                map.value = new AMap.Map("container", {
                    zoom: 12, //初始化地图层级
                    center: location, //初始化地图中心点
                }); // 展示地图 map
                map.value.on("click", function (e) {
                    var lngLat = e.lnglat;
                    mapInfo.value.lng = lngLat.lng;
                    mapInfo.value.lat = lngLat.lat;
                    // let marker = new AMap.Marker({
                    //     position: new AMap.LngLat(lng, lat)
                    // })
                    // this.map.clearMap()// 清除所有覆盖物（点标志）
                    // this.map.add(marker)// 添加点标志
                })
            }
        });
    }).catch(e => {
        console.log(e);
    })
}
const mapInfo = ref({
    address: '',
    lng: '',
    lat: ''
})

const search = () => {
    AMaps.value.plugin('AMap.PlaceSearch', () => {
        var placeSearch = new AMaps.value.PlaceSearch({
            map: map.value,
            pageSize: 1, // 单页显示结果条数
            pageIndex: 1, // 页码
            //autoFitView: true //是否自动调整地图视野使绘制的 Marker 点都处于视口的可见范围
        })
        placeSearch.search(mapInfo.value.address, function (status, result) {
            map.value.clearMap()// 清除所有覆盖物（点标志）
            var pois = result.poiList.pois;
            var poi = pois[0];
            var marker = new AMaps.value.Marker({
                position: poi.location,   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                title: poi.name
            })
            map.value.add(marker)
            let infoWindow = new AMaps.value.InfoWindow({
                isCustom: true, //是否自定义信息窗体
                content: `<div style="background-color: white;padding: 0 5px; border-radius: 5px;border: 1px solid #cccccc;"> 地址：${poi.name}</div>`,
                closeWhenClickMap: true,
                zIndex: 999,
                offset: new AMaps.value.Pixel(16, -35)
            });
            infoWindow.open(map.value, marker.getPosition());
            map.value.setFitView();

            // mapInfo.value.lng = lngLat.lng;
            // mapInfo.value.lat = lngLat.lat;
            // marker添加地图上
            // marker.value = new AMaps.value.Marker({
            //     position: [result.poiList.pois[0].location.lng, result.poiList.pois[0].location.lat]
            // });
            // const infoWindow = new AMaps.value.InfoWindow({
            //     content: `<div style="">${result.poiList.pois[0].name}</div>`, // 设置气泡内容
            //     offset: new AMaps.value.Pixel(0, -30) // 设置气泡偏移量，使其位于标记点正上方
            // });
            // infoWindow.open(map.value, marker.value.getPosition()); // 在地图上打开信息窗口，并指定打开的位置为标记点的位置
            //map.value.add(marker.value); //添加到地图
        })
    })
}

const fileList1 = ref([])
const handleRemove1 = (file) => {
    fileList1.value = []
    quanshuForms.value.propertyCert = ''
}
const uploadSuccess1 = (res) => {
    if (res.code != 200) {
        ElMessage({
            type: 'error',
            message: '上传失败' + res.msg
        })
        fileList1.value.pop()
        return
    }
    quanshuForms.value.propertyCert = res.result
}
const fileList2 = ref([])
const handleRemove2 = (file) => {
    fileList2.value = []
    quanshuForms.value.map = ''
}
const uploadSuccess2 = (res) => {
    if (res.code != 200) {
        ElMessage({
            type: 'error',
            message: '上传失败' + res.msg
        })
        fileList2.value.pop()
        return
    }
    quanshuForms.value.map = res.result
}
const fileList3 = ref([])
const handleRemove3 = (file) => {
    fileList3.value = []
    quanshuForms.value.splitting = ''
}
const uploadSuccess3 = (res) => {
    if (res.code != 200) {
        ElMessage({
            type: 'error',
            message: '上传失败' + res.msg
        })
        fileList3.value.pop()
        return
    }
    quanshuForms.value.splitting = res.result
}
const fileList4 = ref([])
const handleRemove4 = (file) => {
    fileList4.value = []
    quanshuForms.value.erCode = ''
}
const uploadSuccess4 = (res) => {
    if (res.code != 200) {
        ElMessage({
            type: 'error',
            message: '上传失败' + res.msg
        })
        fileList4.value.pop()
        return
    }
    quanshuForms.value.erCode = res.result
}
const fileList5 = ref([])
const handleRemove5 = (file) => {
    fileList5.value = []
    waiguanForms.value.picture = ''
}
const uploadSuccess5 = (res) => {
    if (res.code != 200) {
        ElMessage({
            type: 'error',
            message: '上传失败' + res.msg
        })
        fileList5.value.pop()
        return
    }
    waiguanForms.value.picture = res.result
    waiguanForm.value.validateField('picture')
}
const svgUrl = ref('')
svgUrl.value = import.meta.env.VITE_BASE_PATH + '/manager/building/floor/save/picture'
const fileList6 = ref([])
const uploadSuccess6 = (res, row) => {
    fileList6.value = []
    // if (res.code != 200) {
    //     ElMessage({
    //         type: 'error',
    //         message: '上传失败' + res.msg
    //     })
    //     fileList5.value.pop()
    //     return
    // }
    // waiguanForms.value.picture = res.result
    // waiguanForm.value.validateField('picture')
    savePicture({ floorId: row.id, picture: res.result }).then(result => {
        getLouCengData()
    })
}
const removeSvg = (id) => {
    ElMessageBox.confirm(
        '确认解绑?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        const res = await removePicture(id)
        if (res.code === 200) {
            ElMessage({
                type: 'success',
                message: '解绑成功!'
            })
            getLouCengData()
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消解绑'
        })
    })
}
let dialogVisible = ref(false)
let dialogImageUrl = ref()

//图片预览
const handlePicturePreview = (file, files) => {
    dialogImageUrl.value = file.url;
    dialogVisible.value = true
}

const fangjianData = ref([])
const fangjianForms = ref({
    floorId: ''
})
const getFangJianData = async () => {
    const res = await getFangJianList(fangjianForms.value.floorId)
    if (res.code == 200) {
        fangjianData.value = res.result
    }
}
const fangjianDialog = ref(false)
const handleClose7 = () => {
    fangjianDialog.value = false
}
const openFangJian = (id) => {
    loucengForms.value.buildingId = id
    getLouCengData('floorId')
    fangjianDialog.value = true
}
const fjDialog = ref(false)
const handleClose8 = () => {

    fjDialog.value = false
}
const closeDialog8 = () => {
    fangjianArr.value = []
    fjDialog.value = false
}
const fangjianArr = ref([])
const addFangJian = () => {
    fjDialog.value = true
}
const addFj = () => {
    fangjianArr.value.push({
        floorId: loucengData.value[currentLouCeng.value].id,
        roomNo: '',
        roomArea: '',
        notes: ''
    })
}
const confirmFj = async () => {
    let res = await createFangJian({ rooms: fangjianArr.value })
    if (res.code == 200) {
        ElMessage({
            type: 'success',
            message: '添加成功!'
        })
        fangjianArr.value = []
        fjDialog.value = false
        getFangJianData()
    }
}

const deleteFj = (index) => {
    fangjianArr.value.splice(index, 1)
}
const editRoom = async () => {
    let params = fangjianData.value.map(item => {
        return {
            floorId: item.floorId,
            notes: item.notes,
            roomArea: item.roomArea,
            roomId: item.id,
            roomNo: item.roomNo,
            usedUnit: item.usedUnit
        }
    })
    let res = await updateFangJian({ rooms: params })
    if (res.code == 200) {
        ElMessage({
            type: 'success',
            message: '保存成功!'
        })
        fangjianDialog.value = false
        getTableData()
    }
}
const dialogVisible2 = ref(false)
const dialogImageUrl2 = ref('')
const yulan = (url) => {
    dialogVisible2.value = true
    dialogImageUrl2.value = url
}

const currentLouCeng = ref(0)

const handleClose9 = () => {
    cardDialog.value = false
}
const syxx = ref(null)
const tabChange = () => {
    //syxx.value&&syxx.value.scrollIntoView({ behavior: 'smooth', block: 'start' })
}
</script>

<style lang="scss">
.gva-table-box {
    .header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .left {
            display: flex;
            align-items: center;

            .result {
                width: 60px;
                height: 26px;
                border-radius: 26px;
                display: flex;
                justify-content: center;
                align-items: center;
                color: #0256ff;
                background-color: #E5EEFF;
                margin-right: 6px;
            }

            .blue {
                color: #0256ff;
                margin-left: 4px;
            }
        }
    }

    .list {
        .item {
            display: flex;
            background-color: rgba(229, 238, 255, 0.4);
            padding: 10px;
            margin: 10px 0;

            .left {
                width: 280px;
                height: 180px;
                margin-right: 10px;
            }

            .right {
                flex: 1;

                .area-title {
                    font-size: 16px;
                    color: #333333;
                    font-weight: bold;
                    padding-bottom: 10px;
                    border-bottom: 1px solid #E7ECF1;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                }

                .info-block {
                    display: flex;

                    .info-item {
                        height: 30px;
                        margin-right: 5px;
                        flex: 1;
                        display: flex;
                        align-items: center;
                        overflow: hidden;
                        white-space: nowrap;
                        text-overflow: ellipsis;

                        .label {
                            font-size: 14px;
                            color: #606266;
                            line-height: 20px;
                        }

                        .info {
                            flex: 1;
                            font-size: 14px;
                            color: #303133;
                            overflow: hidden;
                            white-space: nowrap;
                            text-overflow: ellipsis;

                            .unit {
                                font-size: 12px;
                                color: #606266;
                            }
                        }
                    }
                }

                .link-tile-list {
                    width: 100%;
                    display: flex;

                    .link-tile {
                        font-size: 14px;
                        color: #4E7DFD;
                        min-width: 72px;
                        padding: 0 20px;
                        line-height: 26px;
                        height: 26px;
                        border-radius: 6px;
                        border: 1px solid #4E7DFD;
                        background: #FFFFFF;
                        text-align: center;
                        cursor: pointer;
                        margin-top: 10px;
                        margin-right: 10px;
                    }
                }
            }
        }
    }
}

.loudong-drawer {
    .section-title {
        font-weight: bold;
        font-size: 20px;
        line-height: 33px;
        padding: 8px 0 4px 14px;
        color: #4E7DFD;
        border-bottom: 1px solid #E7ECF1;
        position: relative;
        margin-bottom: 20px;
    }

    .section-title:before {
        content: '';
        position: absolute;
        top: 17px;
        left: 0;
        width: 6px;
        height: 14px;
        border-radius: 3px;
        background: #4E7DFD;
    }
}

.quanshu-top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
    border-bottom: 1px solid #E7ECF1;

    div {
        font-size: 20px;
    }

    .section-title {
        margin: 0;
        border: none;
    }
}

.tabs {
    display: flex;

    .tab {
        cursor: pointer;
        padding: 0 16px 10px 16px;
    }

    .active {
        border-bottom: 2px solid #4E7DF7;
    }
}

.fangjian-action {
    display: flex;
    justify-content: space-between;
    margin: 10px 0;
    color: #4E7DF7;
    cursor: pointer;

    .right-action {
        display: flex;
    }
}

#container {
    width: 100%;
    height: 100%;
}
</style>